package com.wxproject.demo.Controller;

import com.wxproject.demo.Common.lang.ResultBody;
import com.wxproject.demo.Entity.AO.FolderCreateAO;
import com.wxproject.demo.Entity.VO.FolderVO;
import com.wxproject.demo.Entity.VO.NextFileVO;
import com.wxproject.demo.Entity.VO.UpLoadFileVO;
import com.wxproject.demo.Service.UserFileService;
import com.wxproject.demo.Utils.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zqf
 * @date 2021/4/11 21:37
 * @description
 */
@RestController
public class FileUpLoadController {
    @Autowired
    private UserFileService userFileService;

    //用户删除自己的文件
    @PostMapping("/deleteFile/{id}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody deleteFile(@PathVariable("id") String id, HttpServletRequest req) {
        String userId = JWTUtil.getUserId(req.getHeader("Token"));
        if (userFileService.deleteFileById(userId, id, DateUtils.getDate()) != 0) {
            return ResultBody.ok().message("删除成功");
        }
        return ResultBody.error().message("无法删除");
    }

    //用户公开文件
    @PostMapping("/publicFile/{id}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody publicFile(@PathVariable("id") String id, HttpServletRequest req) {
        String userId = JWTUtil.getUserId(req.getHeader("Token"));
        if (userFileService.publicFile(id, userId, DateUtils.getDate()) != 0) {
            return ResultBody.ok().message("修改成功");
        }
        return ResultBody.error().message("无法修改");
    }

    //获得某用户公开的文件
    @GetMapping("/getPublicFile/{id}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody getPublicFile(@PathVariable("id") String id) {
        return ResultBody.ok().data("userFile", userFileService.getPublicFile(id));
    }

    //用户修改文件是否公开(state为0表示不公开，为1表示公开)
    @PostMapping("/alterFilePublic/{id}/{state}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody alterFilePublic(HttpServletRequest req, @PathVariable("id") String id, @PathVariable("state") Integer state) {
        if (state != 0 && state != 1) {
            return ResultBody.error().message("state只能为0或者为1");
        }
        String userId = JWTUtil.getUserId(req.getHeader("Token"));
        userFileService.alterFilePublic(userId, id, state, DateUtils.getDate());
        return ResultBody.ok().message("修改成功");
    }

    //上传图片返回链接
    @PostMapping("/uploadImage")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        return UploadUtil.uploadFileReturnUrl(file);
    }

    //创建文件夹
    @PostMapping("/createFolder")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody createFolder(@RequestBody @Validated FolderCreateAO folderCreateAO, HttpServletRequest req) {
        String folderId = String.valueOf(SnowFlake.nextId());
        folderCreateAO.setId(folderId);
        folderCreateAO.setUserId(JWTUtil.getUserId(req.getHeader("Token")));
        if (userFileService.createFolder(folderCreateAO) != 0) {
            return ResultBody.ok().message("创建成功").data("folderId",folderId);
        }
        return ResultBody.error().message("创建失败");
    }

    //用户上传到文件夹
    @PostMapping("/UserFileUpload/{id}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody upload(@PathVariable("id") String id, @RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        UploadUtil.uploadFile(file, request, id);
        return ResultBody.ok().message("上传成功");
    }


    //用户获得自己的文件
    @GetMapping("/getMyFileList")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody getMyFileList(HttpServletRequest req) {
        String userId = JWTUtil.getUserId(req.getHeader("Token"));
        List<UpLoadFileVO> userFile = userFileService.getMyFileList(userId);
        for (int i = 0; i < userFile.size(); i++) {
            userFile.get(i).setMemorySize(FileSizeUtil.getNetFileSizeDescription(Long.parseLong(userFile.get(i).getMemorySize())));
        }
        return ResultBody.ok().data("userFile", userFile);
    }

    //用户获取所有一级文件夹
    @GetMapping("/getMyFolder")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody getMyFolder(HttpServletRequest rq) {
        String userId = JWTUtil.getUserId(rq.getHeader("Token"));
        List<FolderVO> folderList = userFileService.getMyFolder(userId);
        return ResultBody.ok().data("folderList", folderList);
    }

    //获得下一级的文件夹和文件
    @GetMapping("/getNextFolder/{id}")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody getNextFolder(@PathVariable("id") String id) {
        NextFileVO fileList = userFileService.getNextFolder(id);
        return ResultBody.ok().data("folderAndFile", fileList);
    }

    //搜索用户公开的文件
    @GetMapping("/searchFile")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody searchFile(@RequestParam("name")String name,@RequestParam("page")Integer page,
                                 @RequestParam("pageSize")Integer pageSize){
        List<Object> res = userFileService.searchFile(name,page,pageSize);
        List<UpLoadFileVO> upLoadFileVO = (List<UpLoadFileVO>) res.get(0);
        for (UpLoadFileVO loadFileVO : upLoadFileVO) {
            loadFileVO.setMemorySize(FileSizeUtil.getNetFileSizeDescription(Long.parseLong(loadFileVO.getMemorySize())));
        }
        Map<String,Object> ans = new HashMap<>();
        Integer totalSize = Integer.parseInt(res.get(1).toString().substring(1,res.get(1).toString().length()-1));
        Integer totalPage = (int)Math.ceil(Double.parseDouble(res.get(1).toString().substring(1,res.get(1).toString().length()-1))/pageSize);
        ans.put("TotalSize",totalSize);
        ans.put("PageInfo",upLoadFileVO);
        ans.put("TotalPage",totalPage);
        return ResultBody.ok().data("res",ans);
    }

    //获得所有公开文件
    @GetMapping("/getPublicFile")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody getPublicFile(@RequestParam("page")Integer page,
                                 @RequestParam("pageSize")Integer pageSize){
        List<Object> res = userFileService.getAllPublicFile(page,pageSize);
        List<UpLoadFileVO> upLoadFileVO = (List<UpLoadFileVO>) res.get(0);
        for (UpLoadFileVO loadFileVO : upLoadFileVO) {
            loadFileVO.setMemorySize(FileSizeUtil.getNetFileSizeDescription(Long.parseLong(loadFileVO.getMemorySize())));
        }
        Map<String,Object> ans = new HashMap<>();
        Integer totalSize = Integer.parseInt(res.get(1).toString().substring(1,res.get(1).toString().length()-1));
        Integer totalPage = (int)Math.ceil(Double.parseDouble(res.get(1).toString().substring(1,res.get(1).toString().length()-1))/pageSize);
        ans.put("TotalSize",totalSize);
        ans.put("PageInfo",upLoadFileVO);
        ans.put("TotalPage",totalPage);
        return ResultBody.ok().data("res",ans);
    }

    //上传至公开页面
    @PostMapping("/uploadPublicFile")
    @RequiresRoles(logical = Logical.OR, value = {"user"})
    public ResultBody uploadPublicFile(HttpServletRequest rq,@RequestParam("file") MultipartFile file,@RequestParam("introduce")String itr) throws IOException {
       return UploadUtil.uploadPublicFile(file,rq,itr);

    }
}
